<template>
  <div>
    <div class="box-border p-12px">
      <el-form ref="formRef" :rules="rules" :model="submitForm" label-width="100px" class="mt-12px">
        <div>
          <SubTitle title="基本信息" />
          <el-form-item label="上级节点：" prop="parentId">
            <!-- <ns-input v-model="submitForm.parentId" clearable placeholder="请输入策略名称" /> -->
            <el-cascader
              v-model="submitForm.parentId"
              placeholder="当前为根节点"
              :props="cascaderProps"
              :options="treeList"
              filterable
              clearable
            />
          </el-form-item>
          <el-form-item label="分类名称：" prop="cnName">
            <ns-input
              v-model="submitForm.cnName"
              clearable
              placeholder="请输入分类名称"
              maxlength="100"
            />
          </el-form-item>
          <el-form-item label="分类描述：" prop="description">
            <ns-input v-model="submitForm.description" clearable placeholder="请输入分类描述" />
          </el-form-item>
          <el-form-item label="节点类型：" prop="nodeType">
            <el-radio-group v-model="submitForm.nodeType">
              <el-radio label="中间节点">中间节点</el-radio>
              <el-radio label="末节点">末节点</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="策略设置" />
          <el-form-item label="绑定策略：" prop="strategyId">
            <el-select
              v-model="submitForm.strategyId"
              clearable
              placeholder="请选择绑定策略"
              filterable
              :filter-method="filterMethod"
            >
              <el-option
                v-for="(strategy, strategyIndex) in strategyList"
                :key="strategyIndex"
                :label="strategy.strategyName"
                :value="strategy.id"
                @click="strategyChange(strategy)"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="等级设置" />
          <el-form-item label="绑定等级：" prop="levelCode">
            <el-select v-model="submitForm.levelCode" clearable placeholder="请选择绑定等级">
              <el-option
                v-for="(level, levelIndex) in levelList"
                :key="levelIndex"
                :label="level.levelName"
                :value="level.levelCode"
                @click="levelChange(level)"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Plus, Minus, Close } from '@element-plus/icons-vue'
import {
  classificationCreate,
  classificationUpdate,
  classificationTree
} from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { strategyPage } from '@/api/strategyManage/strategy/index'

import SubTitle from '@/components/SubTitle/index.vue'
const route = useRoute()
const message = useMessage() // 消息弹窗
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const cascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})

const tabName = ref('column')
const tabNameList = {
  column: '字段识别规则',
  table: '表识别规则',
  file: '文件识别规则'
}

const formRef = ref()
const submitForm = ref({
  parentId: '',
  cnName: '',
  description: '',
  nodeType: '',
  strategyName: '',
  levelName: ''
})
const isRequired = computed(() => !!submitForm.value.strategyId)
const rules = computed(() => ({
  cnName: [{ required: true, message: '分类名称为空', trigger: 'blur' }],
  nodeType: [{ required: true, message: '请选择节点类型', trigger: 'change' }],
  levelCode: [{ required: isRequired.value, message: '请选择绑定等级', trigger: 'change' }]
}))
const confirm = async () => {
  const apiInterface = props.params.id ? classificationUpdate : classificationCreate
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await apiInterface({
        ...submitForm.value,
        standardId: route.query.id
      })
      console.log('data', data)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

const levelChange = (e) => {
  console.log('e', e)
  submitForm.value.levelName = e.levelName
}
const strategyChange = (e) => {
  console.log('e', e)
  submitForm.value.strategyName = e.strategyName
}

const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}
const strategyList = ref([])
const strategyListCopy = ref([])
const getStrategyList = async () => {
  const { data } = await strategyPage({ page: 1, pageSize: 999, type: 'amp' })
  console.log('data', data)
  strategyListCopy.value = data
  strategyList.value = data
}

const treeList = ref()
const getClassificationTree = async () => {
  const data = await classificationTree({ standardId: route.query.id })
  console.log('data', data)
  treeList.value = traverseTree(data)
  console.log('treeList.value', treeList.value)
}
function traverseTree(data) {
  const updatedTree = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.id == props.params.id) {
      node.disabled = true
      disableDescendants(node.children)
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}
function disableDescendants(children) {
  if (children && children.length > 0) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i]
      children[i].disabled = true // 将子孙节点设置为 disabled
      disableDescendants(child.children) // 递归将子孙节点的子孙节点都设置为 disabled
      children[i] = child
    }
  }
}

const filterMethod = (query) => {
  const keywords = query.split('+') // 将查询字符串按 '+' 分割成关键词数组
  console.log(keywords)
  strategyList.value = strategyListCopy.value.filter((item) => {
    return keywords.every((keyword) =>
      item?.strategyName?.toLowerCase().includes(keyword.toLowerCase())
    )
  })
}

onMounted(() => {
  getClassificationTree()
  getLevelList()
  getStrategyList()
  if (props.params.id) {
    submitForm.value = props.params
    if (!submitForm.value.nodeType) {
      submitForm.value.nodeType = '中间节点'
    }
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
